import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import router from '@/router'
export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref('')
    const userInfo = ref('')
    //登录
    const userLogin = async (data) => {
      const res = await reqLogin(data)
      if (res.code === 200) {
        token.value = res.data
        // getUserInfo()
        return 'ok'
      } else {
        return Promise.reject(new Error(res.data))
      }
    }
    //获取用户信息
    const getUserInfo = async () => {
      const res = await reqUserInfo()
      userInfo.value = res.data
    }
    // 退出登录
    const userLogout = async () => {
      console.log('0000')
      const res = await reqLogout()
      if (res.code == 200) {
        token.value = ''
        userInfo.value = ''
        router.push('/login')
      }
    }

    return {
      token,
      userLogin,
      getUserInfo,
      userLogout,
      userInfo
    }
  },
  {
    persist: true
  }
)
